// 会员服务模块

// 模拟用户数据和会员状态
let currentUser = null;

// 会员等级配置
const membershipLevels = {
  bronze: { name: '青铜会员', color: '#cd7f32', privileges: ['基础内容访问', '每日签到'] },
  silver: { name: '白银会员', color: '#c0c0c0', privileges: ['高级内容访问', '专属头像框', '减少广告'] },
  gold: { name: '黄金会员', color: '#ffd700', privileges: ['全部内容访问', '专属客服', '独家活动邀请', '高速加载'] }
};

// 用户数据（模拟）
const mockUsers = {
  'user@example.com': { id: 1, username: '普通用户', email: 'user@example.com', password: 'password', membershipLevel: null, isMember: false },
  'member@example.com': { id: 2, username: '会员用户', email: 'member@example.com', password: 'password', membershipLevel: 'bronze', isMember: true },
  'vip@example.com': { id: 3, username: 'VIP用户', email: 'vip@example.com', password: 'password', membershipLevel: 'gold', isMember: true }
};

// 登录功能
export const login = (email, password, rememberMe = false) => {
  const user = mockUsers[email];
  if (user && user.password === password) {
    currentUser = { ...user };
    
    // 根据rememberMe决定是否在localStorage中保存用户状态
    if (rememberMe) {
      localStorage.setItem('currentUser', JSON.stringify(currentUser));
    } else {
      // 使用sessionStorage存储，会话结束后自动清除
      sessionStorage.setItem('currentUser', JSON.stringify(currentUser));
    }
    
    return { 
      success: true, 
      user: currentUser,
      redirectUrl: getRedirectUrlForUser(currentUser) // 返回适合该用户的跳转URL
    };
  }
  return { success: false, error: '邮箱或密码错误' };
};

// 根据用户类型获取合适的跳转URL
const getRedirectUrlForUser = (user) => {
  // 检查用户是否有尝试访问但被重定向到登录的页面
  const redirectUrl = localStorage.getItem('redirectUrl');
  if (redirectUrl) {
    localStorage.removeItem('redirectUrl');
    return redirectUrl;
  }
  
  // 根据用户类型决定跳转页面
  if (user.isMember) {
    // 会员用户可以跳转到会员中心
    return '/membership';
  }
  
  // 普通用户默认跳转到首页
  return '/';
};

// 注册功能
export const register = (username, email, password) => {
  if (mockUsers[email]) {
    return { success: false, error: '该邮箱已被注册' };
  }
  
  const newUserId = Object.keys(mockUsers).length + 1;
  const newUser = {
    id: newUserId,
    username,
    email,
    password,
    membershipLevel: null,
    isMember: false
  };
  
  mockUsers[email] = newUser;
  currentUser = { ...newUser };
  localStorage.setItem('currentUser', JSON.stringify(currentUser));
  
  return { 
    success: true, 
    user: currentUser,
    redirectUrl: '/' // 注册成功默认跳转到首页
  };
};

// 退出登录
export const logout = () => {
  currentUser = null;
  localStorage.removeItem('currentUser');
  sessionStorage.removeItem('currentUser');
};

// 获取当前用户
export const getCurrentUser = () => {
  if (!currentUser) {
    // 尝试从localStorage和sessionStorage中恢复用户状态
    const savedUser = localStorage.getItem('currentUser') || sessionStorage.getItem('currentUser');
    if (savedUser) {
      currentUser = JSON.parse(savedUser);
    }
  }
  return currentUser;
};

// 检查用户是否登录
export const isLoggedIn = () => {
  return !!getCurrentUser();
};

// 检查用户是否为会员
export const isMember = () => {
  const user = getCurrentUser();
  return user && user.isMember;
};

// 获取会员等级信息
export const getMembershipInfo = () => {
  const user = getCurrentUser();
  if (user && user.isMember && user.membershipLevel) {
    return membershipLevels[user.membershipLevel] || null;
  }
  return null;
};

// 升级为会员
export const upgradeToMember = (level = 'bronze') => {
  const user = getCurrentUser();
  if (user && membershipLevels[level]) {
    user.membershipLevel = level;
    user.isMember = true;
    
    // 更新存储中的用户信息
    if (localStorage.getItem('currentUser')) {
      localStorage.setItem('currentUser', JSON.stringify(user));
    } else if (sessionStorage.getItem('currentUser')) {
      sessionStorage.setItem('currentUser', JSON.stringify(user));
    }
    
    // 更新mock数据
    if (mockUsers[user.email]) {
      mockUsers[user.email].membershipLevel = level;
      mockUsers[user.email].isMember = true;
    }
    
    return { success: true, user: { ...user } };
  }
  return { success: false, error: '升级失败，请检查会员等级或用户状态' };
};

// 获取所有会员等级
export const getAllMembershipLevels = () => {
  return membershipLevels;
};

// 获取会员特权
export const getMemberPrivileges = () => {
  const info = getMembershipInfo();
  if (info) {
    return info.privileges;
  }
  return [];
};

// 初始化用户状态
export const initializeUser = () => {
  const savedUser = localStorage.getItem('currentUser') || sessionStorage.getItem('currentUser');
  if (savedUser) {
    currentUser = JSON.parse(savedUser);
  }
};

// 保存将要访问的URL，用于登录后重定向
export const saveRedirectUrl = (url) => {
  localStorage.setItem('redirectUrl', url);
};

// 初始化用户状态
initializeUser();